package com.example.springboot3.common.config;

import cn.hutool.core.util.ObjectUtil;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.example.springboot3.common.Constants;
import com.example.springboot3.common.enums.ResultCodeEnum;
import com.example.springboot3.common.enums.RoleEnum;
import com.example.springboot3.entity.Account;
import com.example.springboot3.exception.CustomException;
import com.example.springboot3.service.AdminService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;



@Component
public class JWTInterceptor implements HandlerInterceptor {

    @Resource
    private AdminService adminService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        1.从http请求标头里面拿到token  request.getHeader拿到token
        String token = request.getHeader(Constants.TOKEN);
//        进行判断 token是否为空
        if (ObjectUtil.isNull(token)){
//            如果没拿到，那么再从请求参数拿一次
            request.getParameter(Constants.TOKEN);
        }
//        2.开始执行认证，如果还是没拿到，就返回异常-无效的token
        if (ObjectUtil.isNull(token)){
            throw new CustomException(ResultCodeEnum.TOKEN_INVALID_ERROR);
        }

        Account account = null;

        try {
//        解析token
            String audience = JWT.decode(token).getAudience().get(0);
//        把字符串变成数组
            String userId = audience.split("-")[0];
            String role = audience.split("-")[1];
//        根据用户角色判断用户属于哪个数据库表 然后查询用户数据
            if (RoleEnum.ADMIN.name().equals(role)){
                account = adminService.selectById(Integer.valueOf(userId));
            }
        }catch (Exception e){
            throw new CustomException(ResultCodeEnum.TOKEN_CHECK_ERROR);
        }

//        根据token里面携带的用户id去对应的角色表查询 没查到 所以报了用户不存在的错误
        if (ObjectUtil.isNull(account)){
            throw new CustomException(ResultCodeEnum.TOKEN_INVALID_ERROR);
        }
        try{
//            通过用户的密码作为密钥再次验证token的合法性
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(account.getPassword())).build();
            jwtVerifier.verify(token);  //验证token
        }catch (JWTVerificationException e){
            throw new CustomException(ResultCodeEnum.TOKEN_CHECK_ERROR);
        }

        return true; //返回一个布尔类型的值
    }
}
